import { EventEmitter } from "events";
import { IRpcBase } from "./Rpc";

const headerLen = 2;

/***
 * 处理TCP粘包问题
 */
export class Pipe extends EventEmitter {
  pipe: Buffer = Buffer.alloc(0);
  constructor() {
    super();
  }

  put(buffer: Buffer) {
    this.pipe = Buffer.concat([this.pipe, buffer]);

    while (this.pipe.length > headerLen) {
      const bodyLen = this.pipe.readUint16BE(0);
      const packageLen = headerLen + bodyLen;
      if (this.pipe.length >= packageLen) {
        const data = this.pipe.slice(headerLen, packageLen);
        this.pipe = this.pipe.slice(packageLen);
        this.emit("data", data);
      } else {
        break;
      }
    }
  }

  pack(data: IRpcBase) {
    const body = Buffer.from(JSON.stringify(data));
    const header = Buffer.alloc(2);
    header.writeUInt16BE(body.length);
    const buffer = Buffer.concat([header, body]);
    return buffer;
  }
}
